package com.example.billin.opengltest.shader.program

import android.content.Context
import android.graphics.Color
import android.opengl.GLES20
import com.example.billin.opengltest.R
import com.example.billin.opengltest.shader.render.LittleBallRectColorRender
import java.nio.ByteBuffer
import java.nio.ByteOrder

class RoundPointDisperseProgram(context: Context) :
    Program(context, R.raw.vertex_round_disperse_point, R.raw.fragment_round_dispoint) {

    private val uMatrix = GLES20.glGetUniformLocation(programId, "uMatrix")

    private val aPointSizeColor = GLES20.glGetAttribLocation(programId, "aPointSizeColor")

    private val aPosition = GLES20.glGetAttribLocation(programId, "aPosition")

    private val uColor = GLES20.glGetUniformLocation(programId, "uColor")

    private val uScreenSize = GLES20.glGetUniformLocation(programId, "uScreenSize")

    /**
     * 最高支持一次性绘制 100 个点
     */
    private val floatBuffer = ByteBuffer.allocateDirect(100 * 2 * 4)
        .order(ByteOrder.nativeOrder())
        .asFloatBuffer()


    private var drawSize = 0

    fun setColor(color: Int) {
        GLES20.glUniform4f(
            uColor,
            Color.red(color).toFloat() / 255f,
            Color.green(color).toFloat() / 255f,
            Color.blue(color).toFloat() / 255f,
            Color.alpha(color).toFloat() / 255f
        )
    }

    fun setScreenSize(width: Int, height: Int) {
        GLES20.glUniform2f(uScreenSize, width.toFloat(), height.toFloat())
    }



    fun setMatrix(matrix: FloatArray) {
        GLES20.glUniformMatrix4fv(uMatrix, 1, false, matrix, 0)
    }



    fun bindPositions(points: MutableList<LittleBallRectColorRender.DispersePoint>?, size: Int) {
        floatBuffer.clear()
        for(i in 0 until points!!.size){
            var dispersePoint: LittleBallRectColorRender.DispersePoint? = points?.get(i)
            val dispersePointSize = dispersePoint!!.size.toFloat()
            floatBuffer.put(dispersePoint.agele)
            floatBuffer.put(dispersePoint.distance)
            floatBuffer.put(dispersePoint.radius)
            floatBuffer.put(dispersePointSize)
            floatBuffer.put(dispersePointSize)
        }


        floatBuffer.position(0)
        GLES20.glVertexAttribPointer(aPosition, 3, GLES20.GL_FLOAT, false, 5 * 4, floatBuffer)
        GLES20.glEnableVertexAttribArray(aPosition)

        floatBuffer.position(3)
        GLES20.glVertexAttribPointer(aPointSizeColor, 2, GLES20.GL_FLOAT, false, 5 * 4, floatBuffer)
        GLES20.glEnableVertexAttribArray(aPointSizeColor)


        floatBuffer.position(0)
        drawSize = size
    }

    override fun draw() {
        GLES20.glDrawArrays(GLES20.GL_POINTS, 0, drawSize)
    }
}